package com.ym.jiujiangeyou.bitmap;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ym.jiujiangeyou.R;
import com.ym.jiujiangeyou.util.FileManager;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

// 加载图片
public class ImageLoad1 {

	private BitmapUtil bitmapUtil;

	/**
	 * 线程池
	 */
	private ExecutorService imageThreadPool = null;
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());

	public ImageLoad1() {
		bitmapUtil = BitmapUtil.getInstance();
	}

	
	/** 
	* @return  
	* @retur  ExecutorService 
	* @Description: 获取线层 
	*/
	public ExecutorService getThreadPool() {
		if (imageThreadPool == null) {
			synchronized (ExecutorService.class) {
				if (imageThreadPool == null) {
					imageThreadPool = Executors.newFixedThreadPool(5);
				}
			}
		}
		return imageThreadPool;
	}

	
	/** 
	* @param imageUrl
	* @param imageView  
	* @retur  void 
	* @Description: 提供调用
	*/
	public void loadImage(final String imageUrl, final ImageView imageView) {
		imageViews.put(imageView, imageUrl);
		Bitmap bitmap = bitmapUtil.getBitmapFromLrucache(imageUrl);
		// check in UI thread, so no concurrency issues
		if (bitmap != null) {
			imageView.setImageBitmap(bitmap);
		} else {
			imageView.setImageResource(R.drawable.ic_empty);
			dispayImage(imageUrl, imageView);
		}
	}

	//
	@SuppressLint("HandlerLeak")
	public void dispayImage(final String imageUrl, final ImageView imageView) {
		// Bitmap bitmap = showBitmap(imageUrl) ;
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				String tag = imageViews.get(imageView);
				if (tag != null && tag.equals(imageUrl)) {
					if (msg.obj != null) {
						Bitmap bitmap1 = (Bitmap) msg.obj;
						imageView.setImageBitmap(bitmap1);
					} else {
						imageView.setImageResource(R.drawable.ic_empty);
					}
				}
			}
		};

		getThreadPool().execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Bitmap bitmap = showImage(imageUrl);
				Message message = new Message();
				message.obj = bitmap;
				handler.sendMessage(message);
			}
		});
	}

	// 
	/** 
	* @param imageUrl
	* @return  
	* @retur  Bitmap 
	* @Description: 从sd卡找
	*/
	public Bitmap showImage(String imageUrl) {
		Bitmap bitmap = null ;
		if (imageUrl == null) {
			return null;
		}
		if (!FileManager.isFileExists(imageUrl)) {
			bitmap = downloadImage(imageUrl);
			return bitmap;
		}
		File f = new File(FileManager.getImagePath(imageUrl)) ;
		/* bitmap = BitmapUtil.decodeSampledBitmapFromResource(
				FileManager.getImagePath(imageUrl), 100, 90);*/
		bitmap = BitmapUtil.decodeFile(f) ;
		if (bitmap != null) {
			bitmapUtil.addBitmapToLrucache(imageUrl, bitmap);
		}
		return bitmap;
	}

	
	/** 
	* @param imageUrl
	* @return  
	* @retur  Bitmap 
	* @Description: 下载指定url图片
	*/
	private Bitmap downloadImage(String imageUrl) {
		String imagePath = FileManager.getImagePath(imageUrl);
		Bitmap bitmap = null ;
		HttpURLConnection con = null;
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;
		BufferedInputStream bis = null;
		File imageFile = null;
		try {
			URL url = new URL(imageUrl);
			con = (HttpURLConnection) url.openConnection();
			con.setConnectTimeout(5 * 1000);
			con.setReadTimeout(15 * 1000);
		//	con.setDoInput(true);
		//	con.setDoOutput(true);
			int size = con.getContentLength();
			bis = new BufferedInputStream(con.getInputStream());
			imageFile = new File(imagePath);
			fos = new FileOutputStream(imageFile);
			bos = new BufferedOutputStream(fos);
			byte[] b = new byte[size];
			int length;
			while ((length = bis.read(b)) != -1) {
				bos.write(b, 0, length);
				bos.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (bis != null) {
					bis.close();
				}
				if (bos != null) {
					bos.close();
				}
				if (con != null) {
					con.disconnect();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (imageFile != null) {
			 bitmap = BitmapUtil.decodeFile(imageFile) ;
			if (bitmap != null) {
				bitmapUtil.addBitmapToLrucache(imageUrl, bitmap);
			}
		}
		return bitmap ;
	}

	/**
	 * 取消任务
	 */
	public synchronized void cancelTask() {
		if (imageThreadPool != null) {
			imageThreadPool.shutdownNow();
			imageThreadPool = null;
		}
	}
}
